<?php

class WallConfig extends BaseWallConfig
{
    const TOKEN_ERROR_CODE = 4273;

    /**
     * WARNING: calls the FB API
     */
    public function updatePermissions()
    {
        // is_active = false by default
        if (!$this->is_active)
            return false;

        if (!sfContext::getInstance()->getUser()->hasPagePermission('publish_stream')) {
            $this->is_active = false;
            $this->save();
        }
    }


    public function updateNextRun()
    {
        $delay = 86400 / $this->frequency;
        $this->next_run = date(DATE_ISO8601, time() + $delay);
    }


    public function isImmediate()
    {
        return $this->is_active && $this->state === 'real-time';
    }


    public static function publishJob($job)
    {
        return self::customPublishJob(
            $job,
            $job->getValue('title'),
            $job->getPreview());
    }

    public static function getTokenForPage($page_id) {
        $res = App::call_api(
                        '/'.$page_id.'?fields=access_token',
                        'get');

        if (!is_array($res) || !array_key_exists('access_token', $res))
            throw new sfException("couldn't obtain access_token for page_id #".$page_id, self::TOKEN_ERROR_CODE);

        vtnsLog::debug('Fetched access_token #%s',$res['access_token']);

        return $res['access_token'];
    }


    public static function customPublishJob($job, $custom_title, $custom_job_preview, $caption = null)
    {
        $context = sfContext::getInstance();
        $context->getConfiguration()->loadHelpers(array('I18N'), $context->getModuleName());

        $name = $custom_title;
        if (!$caption)
            $caption = $job->getFormattedLocation($job->Page->Profile->culture ?: 'en');

        try {
            $conn = Doctrine::getTable('Post')->getConnection();
            $conn->beginTransaction();

            $token = self::getTokenForPage($job->page_id);

            $attachment = array(
                'name' => $name,
                'caption' => $caption,
                'access_token' => $token,
                'link' => $job->Page->getCurrentTabUrl().'&app_data='.urlencode('job/'.$job->job_id),
                'description' => $custom_job_preview,
                'actions' => array(array(
                    'name' => __('Share'),
                    'link' => 'http://www.facebook.com/sharer.php?u='.$job->base_url.'?w4r%3Dwall_share'))
                );

            $res = App::call_api(
                            '/'.$job->page_id.'/feed/',
                            'post',
                            $attachment);

            $post = new Post();
            $post->setPageId($job->page_id);
            $post->setPostId($res['id']);
            $post->save();

            $job_post = new JobPost();
            $job_post->setJobId($job->job_id);
            $job_post->setPostId($post['post_id']);
            $job_post->save();
            $job->wall_sent_at = date(DATE_ISO8601);
            $job->save();
            $conn->commit();
        } catch (Exception $e) {
            $conn->rollBack();
            if ($e instanceof FacebookApiException) {
                $message = json_encode($e->getResult());
            } elseif ($e->getCode() === self::TOKEN_ERROR_CODE) {
                $logger = new sfFileLogger(
                    new sfEventDispatcher(),
                    array('file' => sfConfig::get('sf_log_dir').'/api_wall_post_access_token_error.log'));
                $logger->err('Missing token_access for page_id #'.$job->page_id.' / job_id #'.$job->job_id);
                return self::oldcustomPublishJob($job, $custom_title, $custom_job_preview);
            } else {
                $message = $e->getMessage();
            }
            vtnsLog::error('{WallConfig} Exception: %s', $message);
            LogUser::log('error_wall_post', $job->job_id, null, $message.(isset($post['id']) ? ' Facebook return: '.$post['id'] : ''));
            return false;
        }
        return true;
    }

    /**
    * Added in v1.13.4 for compatibility.
    * We need to use this old/deprecated code to post if we don't obtain the
    * page access_token.
    */
    public static function oldcustomPublishJob($job, $custom_title, $custom_job_preview)
    {
        $context = sfContext::getInstance();
        $context->getConfiguration()->loadHelpers(array('I18N'), $context->getModuleName());

        $name = $custom_title;

        $attachment = array(
            'name' => $name,
            'href' => $job->Page->getCurrentTabUrl().'&app_data='.urlencode('job/'.$job->job_id),
            'description' => $custom_job_preview,
            );

        $action_links = array(array(
                'text' => '<fb:intl desc="Link: Name of action performed to apply for a job position posted on a page\'s wall.">Share</fb:intl>',
                'href' => 'http://www.facebook.com/sharer.php?u='.$job->base_url.'?w4r%3Dwall_share'));

        $conn = Doctrine::getTable('Post')->getConnection();
        $conn->beginTransaction();
        try {
            $post_id = App::call_api(array(
                    'method'       => 'stream.publish',
                    'message'      => '',
                    'attachment'   => json_encode($attachment),
                    'action_links' => json_encode($action_links),
                    'target_id'    => '',
                    'uid'          => $job->page_id,
                    ));

            $post = new Post();
            $post->setPageId($job->page_id);
            $post->setPostId($post_id);
            $post->save();

            $job_post = new JobPost();
            $job_post->setJobId($job->job_id);
            $job_post->setPostId($post_id);
            $job_post->save();
            $job->wall_sent_at = date(DATE_ISO8601);
            $job->save();
            $conn->commit();
        } catch (Exception $e) {
            $conn->rollBack();
            vtnsLog::error('{WallConfig} Exception %s', $e->getMessage());
            LogUser::log('error_wall_post', $job->job_id, null, $e->getMessage().' Facebook return: '.(isset($post_id) ? $post_id : ''));
            return false;
        }
        return true;
    }


    public static function publishInstallStory(Page $page)
    {
        $tab_url = $page->getCurrentTabUrl();

        // Do not use images hosted on fbcdn.net
        sfContext::getInstance()->getConfiguration()->loadHelpers('Asset', sfContext::getInstance()->getModuleName());


        try {
            $token = self::getTokenForPage($page->page_id);

            $logo_url = image_path('logo_vtns.png', true);
            $message = '';
            $attachment = array(
                    'name'         => sfContext::getInstance()->getI18N()->__('Check out our job opportunities in the new "%app_name%" tab',array('%app_name%' => sfConfig::get('sf_vtns_app_name'))),
                    'caption'      => sfConfig::get('sf_vtns_app_name'),
                    'access_token' => $token,
                    'link'         => $tab_url,
                    'picture'      => $logo_url,
                    'description'  => sfContext::getInstance()->getI18N()->__('You can now access jobs from top recruiters on our Facebook Page! Check out the opportunities and apply or share them with other students by clicking on the "%app_name%" tab.',array('%app_name%' => sfConfig::get('sf_vtns_app_name'))),
            );
            
            var_dump($attachment);
            /*$post = App::call_api(
                            '/'.$page->page_id.'/feed/',
                            'post',
                            $attachment);*/
        } catch (Exception $e) {
            vtnsLog::error('{WallConfig} publishInstallStory post error: '.$e->getMessage());
            return false;
        }
        return true;
    }
}
